<?php

namespace App\Http\Controllers\Backstage\System;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Lib\FileService\FastDFS;
use App\UploadedFileState;

class BaseUploadController extends Controller
{
    public function doUpload(Request $request)
    {
        $fileEntrys = $request->all();
        $file = null;
        $fileKey = null;
        foreach ($fileEntrys as $key => $value) {
            $file = $value;
            $fileKey = $key;
        }

        if (isset($file)) {
            $fdfs = new FastDFS();
            $fileResult = $fdfs->directSaveFile($file);

            if ($fileResult['status'] === 0) {
                $fileId = $fileResult['group'].'/'.$fileResult['fileName'];
                UploadedFileState::create([
                    'file_id' => $fileId,
                    'state' => 0
                ]);

                return response()->json([
                    'status' => 0,
                    'info' => $fileResult['info'],
                    'fileKey' => $fileKey,
                    'fileId' => $fileId,
                    'filePath' => FastDFS::getFullUrl($fileId)
                ]);
            } else {
                return response()->json([
                    'status' => $fileResult['status'],
                    'info' => $fileResult['info']
                ]);
            }
        }

        return response()->json([
            'status' => 1000,
            'info' => '文件为空'
        ]);
    }

    public function doRichEditorUpload(Request $request)
    {
        $fileEntrys = $request->all();
        $file = null;
        $fileKey = null;
        foreach ($fileEntrys as $key => $value) {
            $file = $value;
            $fileKey = $key;
        }

        if (isset($file)) {
            $fdfs = new FastDFS();
            $fileResult = $fdfs->directSaveFile($file);

            if ($fileResult['status'] === 0) {
                $fileId = $fileResult['group'].'/'.$fileResult['fileName'];
                UploadedFileState::create([
                    'file_id' => $fileId,
                    'state' => 0
                ]);

                return response()->json([
                    'status' => 0,
                    'code' => 0,
                    'msg' => '',
                    'fileKey' => $fileKey,
                    'fileId' => $fileId,
                    'data' => [
                        'src' => FastDFS::getFullUrl($fileId)
                    ]
                ]);
            } else {
                return response()->json([
                    'status' => $fileResult['status'],
                    'info' => $fileResult['info']
                ]);
            }
        }

        return response()->json([
            'status' => 1000,
            'info' => '文件为空'
        ]);
    }
}
